package com.example.www.Controller;

import com.example.www.Base.Result;
import com.example.www.Entity.User;
import com.example.www.Service.UserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/api/login")
    @CrossOrigin
    public Result login(@RequestBody UserParam userParam){
       User user=userService.getUser(0);
       if(user.getUsername().equals(userParam.username)&&user.getPassword().equals(userParam.password)){
           return Result.authenticated();
       }else{
           return Result.unAuthenticated();
       }
    }

    @PostMapping("/api/adduser")
    @CrossOrigin
    public Result addUser(@RequestBody UserParam newuser){
        User user=new User();
        user.setId(0);
        user.setUsername(newuser.username);
        user.setPassword(newuser.password);
        userService.addUser(user);
        return Result.OK();
    }

    @PostMapping("/api/changeuser")
    @CrossOrigin
    public Result changeUser(@RequestBody UserChange userParam){
        User oldUser=userService.getUser(0);
        if(oldUser.getUsername().equals(userParam.oldUsername)&&oldUser.getPassword().equals(userParam.oldPassword)) {
            User user = new User();
            user.setId(0);
            user.setUsername(userParam.username);
            user.setPassword(userParam.password);
            userService.changeUser(user);
            return Result.OK();
        }else{
            return Result.unAuthenticated();
        }
    }

    @GetMapping("/api/isuserexists")
    @CrossOrigin
    public Result isUserExists(){
        User user=userService.getUser(0);
        if (user==null){
            return Result.isUserExists(false);
        }else {
            return Result.isUserExists(true);
        }
    }
}

class UserParam{
    public String username;
    public String password;
}
class UserChange{
    public String oldUsername;
    public String oldPassword;
    public String username;
    public String password;
}